package com.asset.interceptor;

import com.asset.context.BaseContext;
import com.asset.utils.JWTUtil;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            Map<String, Object> claims = JWTUtil.checkToken(token);

            String userId = (String)claims.get("userId");
            BaseContext.setCurrentId(userId);
//            System.out.println("userId"+userId);
//            String currentId = BaseContext.getCurrentId();
//            System.out.println("currentId:"+currentId);
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("访问异常");
            response.setStatus(401);
            //不放行
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocal<Object> threadLocal = new ThreadLocal<>();
        threadLocal.remove();
    }
}
